let vertices = ref []
let faces = ref []
let maxCoord = ref 1.

let ( /| ) (x,y,z) a = (x/.a,y/.a,z/.a)

let abs a =
    if a < 0. then
        (-. a)
    else a

let addVertices x y z =
    maxCoord := max !maxCoord (max (abs x) (max (abs y) (abs z)));
    vertices := (x,y,z)::!vertices

let addFaces v1 v2 v3 =
    faces := (v1,v2,v3)::!faces

let parse file =
    let nbV = ref 0 in
    let continue = ref true in
    let line = ref (input_line file) in
    while (!continue) do
        if ((String.length !line) > 0) then
            if (!line.[0] = 'v') then
                begin
                    nbV := !nbV + 1;
                    Scanf.sscanf !line "v %f %f %f" addVertices;
                end
            else if (!line.[0] = 'f') then
                Scanf.sscanf !line "f %d// %d// %d//" addFaces;
        try
            line := input_line file;
        with
            |End_of_file -> continue := false
     done;
     let tabVertices = Array.make !nbV (0.,0.,0.) in
     tabVertices

let listToTab tab =
    let rec aux l i =
        if i >= 0 then
            match l with
            |e::h -> tab.(i) <- e /| !maxCoord; aux h (i -1)
            |[] -> ()
        else
            ()
    in
    aux !vertices ((Array.length tab) - 1)

let foi = float_of_int

let colorAssoc l (_,_,z) =
    let rec aux = function
        |(h,r,g,b)::l when ((foi h) /. !maxCoord) = z ->
                (foi r /. 255., foi g /. 255., foi b /. 255.)
        |_::l -> aux l
        |[] -> (1.,1.,1.)
    in
    aux l

let colorTab tabVertices l =
    let m = Array.length tabVertices in
    let tab = Array.make m (0.,0.,0.) in
    let i = ref 0 in
    while !i < m do
        tab.(!i) <- colorAssoc l tabVertices.(!i);
        i := !i + 1;
    done;
    tab

let main path =
    if not (Sys.file_exists path) then
        failwith "FileNotFound"
    else
        begin
            vertices := [];
            faces := [];
            let file = open_in path in
            let tabVertices = parse file in
            listToTab tabVertices;
            tabVertices
        end

